<?php
/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/5/20
 * Time: 15:46
 * 登录功能
 */
class Login extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
		
		$this->load->model('user_model');
//		$this->load->model('role_model');
//		$this->load->model('permission_model');
    }
	
	// 登录界面
	public function index() 
	{
		$this->load->view('admin/login/index');
	}
	
    // 登录
    public function login()
    {
        //region CI自带验证
        $config = array(
            array(
                'field' => 'username',
                'label' => '用户名',
                'rules' => 'trim|required',
            ),
            array(
                'field' => 'password',
                'label' => '密码',
                'rules' => 'trim|required',
            )
        );
		$this->form_validation->set_rules($config);
		
		// 开启session
		if (!isset($_SESSION)) {
			session_start();
		}
		$username = $this->input->post('username');
		$row	  = $this->user_model->findUser($username); 	
        $password = $this->input->post('password');
		if (!$row || $row['password'] != $password) error('用户名或者密码不正确');
		
		// 写入session
		$userData = [
			'username'  => $username,
			'userid'    => $row['id'],
			'logintime' => time(),
			'nickname'	=> $row['nickname'],
			'role'		=> $row['role_id']
		];
		
		// 记录每次登录更新用户登录时间
        $this->user_model->edit(array('loginTime' => time()), array('username' => $this->input->post('username')));
		
		$this->session->set_userdata($userData);		
//		$res = $this->session->userdata('username'); // 取出session内容
//		redirect('/home/index');
		success('home/index', '登录成功');
    }

	// 修改密码接口
    public function editPassword()
    {
    	$username = $this->input->post('username');
		$row	  = $this->user_model->findUser($username); 	
        $oldPwd   = $this->input->post('oldPassword');
		$newPwd   = $this->input->post('newPassword');
		$result   = [];
		if ($row) {
			if ($newPwd == $oldPwd) {
				$result = array('error' => '原密码和新密码一致!');    
				                               
			} elseif ($row['password'] != $oldPwd){
	            $result = array('error' => '原密码不正确!'); 
				
	        } else {
	            $editData = array('password' => $newPwd);
	            $where    = array('id' => $row['id']); 
				
				$editResult = $this->user_model->edit($editData, $where);
				if ($editResult) {
                    $result = array('success' => '修改成功!');
                } else {
                	$result = array('error' => '密码修改失败,请联系管理员!');
                }
			}        
		} else {
			$result = array('error' => '用户名不存在!'); 
		}
		echo json_encode($result, JSON_UNESCAPED_UNICODE);
    }

    // 检测用户名是否存在
    public function issetUser()
    {
        $arg = [
            'username' => $_POST['username']
        ];

        $data = $this->user_model->getByFieldQueryData('id,username,password', $arg, 0);
		
        if ($data) {
            $result = [
                'success' => '用户存在'
            ];
        } else {
            $result = [
                'error' => '用户不存在'
            ];
        }
		
        echo json_encode($result, JSON_UNESCAPED_UNICODE);
    }

	// 登出功能
	public function logout()
	{
		$this->session->unset_userdata($userData);
		redirect('admin/login/index');
	}
	
	// 权限测试
//	public function test()
//	{
//		// 访问权限控制
//      $a = '技术,管理员';
//      // 改为根据用户id查询roleId
//      $arg = [
//          'id' => $this->session->userdata('userid')
//      ];
//      $userResult = $this->user_model->getByFieldQueryData('id,role_id', $arg, 0); //根据用户id,查询权限id
//		
//      $roleId = explode(',', $userResult['role_id']);
//		
////        $subUrl = substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '?'));//获取当前的url截取后的字符串
//
//      //供应商是否有别的角色
//      // if($roleId[0] == '供应商'){
//      //     if($_SERVER['REQUEST_URI'] != '/admin/bidding/waitingList?page=1'){
//      //         redirect('/admin/bidding/waitingList?page=1');
//      //     }
//      // }
//
//      foreach ($roleId as $k => $v) {
//          //在根据roleId读取 == name   role表,  读取permission_id
//          $arg = [
//              'name' => $v
//          ];
//          $permissionId[] = $this->role_model->getByFieldQueryData('*', $arg, 0);
//      }
//		
//      $ids = array_column($permissionId, 'permission_id');
//		
//      //在根据permission_id == id 读取 permission
//      foreach ($ids as $k2 => $v2) {
//          $idsData[] = explode(',', $v2);
//
////            $emptyIds = array_unique($ids);  //去除相同的id
//      }
//		
//      foreach ($idsData as $k3 => $v3) {
//          foreach ($v3 as $k4 => $v4) {
//              $arg2 = [
//                  'id' => $v4
//              ];
//				
//              $permissionIdData[] = $this->permission_model->getByFieldQueryData('*', $arg2, 0);
//          }
//
//
//      }
//		dd($permissionIdData);
//      // /admin/check/index?page=1&type=1
//      if (strrpos($_SERVER['REQUEST_URI'], '?')) {
//          $subUrl = substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], '?')); //获取当前的url截取后的字符串
//
//      } else {
//          $subUrl = $_SERVER['REQUEST_URI']; //获取当前的url截取后的字符串
//      }
//
////      $subUrl = '/admin/procurement/barterOrderAddView';
//      foreach ($permissionIdData as $k4 => $v4) {
//          if ($permissionIdData[$k4]) {
//              //在用permission 跟 $_SERVER['REQUEST_URI']  比较,如果相等, 就表示有权限,如果没有就没有
//              $explodeData[] = explode(',', $v4['permission']);  //根据逗号分割字符串成数组
//
//          }
//      }
//
//      foreach ($explodeData as $k5 => $v5) {
//          if (in_array($subUrl, $explodeData[$k5])) {
//              $arr[] = '存在';
//          } else {
//              $arr[] = '不存在';
//          }
//      }
//
//      if(!in_array('存在',$arr)){
//          die( __alert('没有权限!'));
//      }
//	}
	
}